package com.ss.android.article.common;

import android.content.Context;
import android.view.OrientationEventListener;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

public final class ScreenOrientationObserver {
    public final CopyOnWriteArraySet<OrientationChangeListener> mOrientationChangeListenerSet;
    public final MyOrientationEventListener mMyOrientationEventListener;
    public final Context mContext;

    public ScreenOrientationObserver(Context context) {
        this.mOrientationChangeListenerSet = new CopyOnWriteArraySet();
        this.mContext = context.getApplicationContext();
        this.mMyOrientationEventListener = new MyOrientationEventListener(this.mContext);
    }

    public final void reset() {
        this.mMyOrientationEventListener.mLastScreenOrientation = -1;
    }

    public interface OrientationChangeListener {
        void onOrientationChanged(int orientation);
    }

    public final class MyOrientationEventListener extends OrientationEventListener {
        private int mLastScreenOrientation = -1;

        public MyOrientationEventListener(Context context) {
            super(context);
        }

        public int getCurrentScreenOrientation() {
            return mLastScreenOrientation;
        }

        @Override
        public final void onOrientationChanged(int orientation) {
            int screenOrientation;
            if (orientation != -1) {
                if (orientation >= 0 && orientation < 23 || orientation >= 338) {
                    screenOrientation = 1;
                } else if (orientation >= 68 && orientation < 112) {
                    screenOrientation = 8;
                } else if (orientation >= 158 && orientation < 202) {
                    screenOrientation = 9;
                } else if (orientation >= 248 && orientation < 298) {
                    screenOrientation = 0;
                } else {
                    screenOrientation = -1;
                }
                if (this.mLastScreenOrientation == screenOrientation) {
                    return;
                }
                this.mLastScreenOrientation = screenOrientation;
                if (screenOrientation == -1) {
                    return;
                }
                Iterator<OrientationChangeListener> iterator = mOrientationChangeListenerSet.iterator();
                while (iterator.hasNext()) {
                    iterator.next().onOrientationChanged(screenOrientation);
                }
            }
        }
    }
}

